import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { getToken, removeToken } from '@/utils/CookieUtils'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['ok-token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

let showMessage = false

service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code === 0) {
      if (showMessage) {
        Message({ message: res.message || '操作成功', type: 'success' })
      }
      return res
    } else {
      if (res.code === 2000) {
        MessageBox.confirm('用户未登录', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          showClose: false,
          showCancelButton: false,
          closeOnPressEscape: false,
          closeOnClickModal: false
        }).then(() => {
          removeToken()
          // 如果在登录页面则不刷新页面
          const href = window.location.href
          if (href.indexOf('login') === -1) {
            location.reload()
          }
        })
      } else {
        Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    Message({ message: error.message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default {
  get(url, data, show = false) {
    showMessage = show
    return service.get(url, { params: data })
  },
  post(url, data, show = false) {
    showMessage = show
    return service.post(url, data)
  },
  put(url, data, show = false) {
    showMessage = show
    return service.put(url, data)
  },
  delete(url, data, show = false) {
    showMessage = show
    return service.delete(url, { params: data })
  }
}
